Good Programming Practices

Whenever we develop programs, the correctness of the program (whether it produces the "right" results) is a very important concern, but it is not the only concern. Other important factors include efficiency and programming style. Efficiency refers to whether the program runs in a reasonable amount of time and uses a reasonable amount of memory. These guidelines represent some common good practices in programming.

Comments are an important and effective way of making our programs easier to read and understand (as well as debug). Comments are meant for humans to read; in fact, Matlab ignores all comments when it executes code. Comments in Matlab begin with a percent sign ( % ) and continue to the end of the line. Use comments liberally in your code to help you, your collaborator and your instructor understand what your code does and how it does it.

Here's a program that illustrates these guidelines.

     % Program that converts height in feet and inches to meters
     % Author(s): Becky Badger, Bucky Badger
     % Version: 1.0.01  
     % Date: October 1, 2006
    
     % Input the data (may use input command here or read from file)
     MPI = 0.0254 ;               % meters/inch conversion constant
     inputHeight = [ 6 4 ] ;      % height in feet and inches as may have
     feet = inputHeight(1) ;      %         been entered by the user
     inch = inputHeight(2) ;

     % Calculate values
     heightIn = feet*12 + inch ;  % get total height in inches
     heightM  = heightIn * MPI ;  % convert to meters

     % Output the height to the user in an easy to read form
     disp( ['The height ', num2str(feet), 'feet ', num2str(in), ...
            'inches = ', num2str(heightM), ' meters']);